import { userRegisterUsingPost } from '@/services/pqbi/userController';
import { history } from '@umijs/max';
import { Button, Form, FormProps, Input, message } from 'antd';
import React from 'react';

const Register: React.FC = () => {
  const [submitting, setSubmitting] = React.useState(false);
  /**
   * 注册请求处理
   */
  const handleSubmit = async (values: API.UserRegisterRequest) => {
    if (values.userPassword !== values.checkPassword) {
      message.error('两次输入的密码不一致');
      return;
    }
    setSubmitting(true);
    try {
      // 注册
      const res = await userRegisterUsingPost({
        userAccount: values.userAccount,
        userPassword: values.userPassword,
        checkPassword: values.checkPassword,
      });

      if (res.code === 0) {
        message.success('注冊成功');
        // 跳转到登录页
        history.push('/user/login');
      } else {
        message.error(res.message || '注册失败');
      }
    } catch (error) {
      message.error('注册失败，请重试！');
    }finally {
      setSubmitting(false);
    }
  };

  return (
    <Form
      name="register"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 600 }}
      onFinish={handleSubmit}
      autoComplete="off"
    >
      {/* 用户账号 */}
      <Form.Item
        label="注册账户"
        name="userAccount"
        rules={[{ required: true, message: '请输入注册账号' },]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="注册密码"
        name="userPassword"
        rules={[{ required: true, message: '请输入注册密码' }]}
      >
        <Input.Password />
      </Form.Item>
      <Form.Item
        label="验证密码"
        name="checkPassword"
        dependencies={['userPassword']}
        rules={[
          { required: true, message: '请确认密码' },
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item label={null}>
        <Button type="primary" htmlType="submit">
          注冊
        </Button>
      </Form.Item>
    </Form>
  );
};
export default Register;
